#/usr/bin/python
# -*- coding: utf-8 -*-

from mpi4py import MPI
import sys
sys.path.append('../../../icafe')
import parameters

from domain import DomainDecorator, GlobalDomain, SubDomain


def decorateDomain(domain, decorator=None, master=None):
    '''
        Method to decorate a the domain of the current worker process.  
    '''
    if not decorator:
        decorator = master.recv(source=0)
    
    if isInstance(decorator, DomainDecorator):
        domain = decorator(domain)
    
    return domain

def returnDomain(domain, master):
    
    try:
        domain.unSpawnProcesses()
    except AttributeError:
        pass
    
    master.gather(domain,root=0)
    
    return 0
    
# init mpi environment
args = sys.argv[1:]

coworkers = MPI.COMM_WORLD
master = MPI.Comm.Get_parent()

# initialize subdomain:
domain = master.recv(source=0)

# wait for jobs:
while 1:
    msg = domain.waitForJob()
    if msg=='disconnect':
        break
    elif msg=='domain':
        returnDomain(domain,master)
    elif isInstance(msg,DomainDecorator):
        domain = decorateDomain(domain, msg, master)
    else:
        raise NotImplementedError(msg)
        
           
master.Disconnect()

